//
//  ZJFMapViewController.m
//  OurTourism
//
//  Created by 张金峰 on 15/12/5.
//  Copyright © 2015年 Devil_Coming. All rights reserved.
//

#import "ZJFMapViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "Header.h"
@interface ZJFMapViewController ()<MKMapViewDelegate, CLLocationManagerDelegate>

@property(nonatomic, strong) UIButton *normalBtn;
@property(nonatomic, strong) UIButton *moonBtn;
@property(nonatomic, strong) MKMapView *mapView;
@property(nonatomic, strong) CLLocationManager *manager;
@property(nonatomic, strong) CLLocation *location;
@property(nonatomic, strong) CLGeocoder *reocoder;
@property(nonatomic, strong) MKUserLocation *userLocation;

@end

@implementation ZJFMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:250 / 255. green:246 / 255. blue:232 / 255. alpha:1];
//    self.navigationItem.title = self.naviTitle;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 25, 25);
    [backBtn setImage:[UIImage imageNamed:@"iconfont-iconfonticonfontjiantouzuo11@2x"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    
    //初始化地图
    self.mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.mapView];
    self.mapView.showsUserLocation = YES;
    self.mapView.showsScale = YES;
    self.mapView.showsCompass = YES;
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    self.mapView.delegate = self;
    
    //这里是对地图的范围进行约束
    MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1);
    //double lat = [self.locationDic[@"lat"] doubleValue];
   // double lng = [self.locationDic[@"lng"] doubleValue];
   // CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(lat, lng);
  //  MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, span);
  //  [self.mapView setRegion:region animated:YES];
    
    //初始化manager
    self.manager = [[CLLocationManager alloc] init];
    [self.manager requestWhenInUseAuthorization];
    self.manager.delegate = self;
    self.manager.distanceFilter = 50;
    self.manager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.manager startUpdatingLocation];
    
    MKPointAnnotation *annotaion = [[MKPointAnnotation alloc] init];
    //annotaion.coordinate = coordinate;
   // annotaion.title = self.naviTitle;
    
    [self.mapView addAnnotation: annotaion];
    
    self.normalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.normalBtn.frame = CGRectMake(WIDTH - 140, 20, 50, 30);
    self.normalBtn.backgroundColor = [UIColor blackColor];
    self.normalBtn.alpha = .8;
    [self.normalBtn setTitle:@"标准" forState:UIControlStateNormal];
    [self.normalBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.normalBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    self.normalBtn.titleLabel.layer.cornerRadius = 10;
    [self.normalBtn addTarget:self action:@selector(mapTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.normalBtn];
    
    self.moonBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.moonBtn.frame = CGRectMake(WIDTH - 90, 20, 50, 30);
    self.moonBtn.backgroundColor = [UIColor grayColor];
    self.moonBtn.alpha = .8;
    [self.moonBtn setTitle:@"卫星" forState:UIControlStateNormal];
    [self.moonBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.moonBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    self.moonBtn.titleLabel.layer.cornerRadius = 10;
    [self.moonBtn addTarget:self action:@selector(mapTypeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.moonBtn];
    
    UIButton *myLocationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    myLocationBtn.frame = CGRectMake(WIDTH - 50, HEIGTH - 130, 40, 40);
    [myLocationBtn setImage:[UIImage imageNamed:@"iconfont-dingwei"] forState:UIControlStateNormal];
    [myLocationBtn addTarget:self action:@selector(myLocationAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myLocationBtn];
}

- (void)mapTypeAction:(UIButton *)sender
{
    if (sender == self.normalBtn) {
        self.mapView.mapType = 0;
        self.normalBtn.backgroundColor = [UIColor blackColor];
        self.moonBtn.backgroundColor = [UIColor grayColor];
    }
    if (sender == self.moonBtn) {
        self.mapView.mapType = 1;
        self.normalBtn.backgroundColor = [UIColor grayColor];
        self.moonBtn.backgroundColor = [UIColor blackColor];
    }
}

- (void)myLocationAction
{
    MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1);
    CLLocationCoordinate2D coordinate = self.location.coordinate;
    MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, span);
    [self.mapView setRegion:region animated:YES];
}

#pragma mark CLLocationManager Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    //获取当前位置
    self.location = [locations lastObject];
    //逆地理方法
    [self reocoderMethod];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd-hh:mm:ss";
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"定位失败原因:%@", error);
}

#pragma mark - 逆地理转换方法(将经纬度转换成具体位置)
- (void)reocoderMethod
{
    //初始化CLGeocoder
    self.reocoder = [[CLGeocoder alloc] init];
    
    //逆地理转换
    [self.reocoder reverseGeocodeLocation:self.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (error == nil && placemarks.count > 0) {
            //这个类用来存储位置信息
            CLPlacemark *placeMark = placemarks.firstObject;
            
            //蓝点得文字
            self.mapView.userLocation.title = placeMark.locality;
            self.mapView.userLocation.subtitle = placeMark.addressDictionary[@"FormattedAddressLines"][0];
            
            
        } else if (error == nil && placemarks.count == 0) {
            
            NSLog(@"没有返回结果");
            
        } else {
            
            NSLog(@"逆地理方法错误: %@", error);
        }
    }];
}

#pragma mark - mapView Delegate

//以下是创建大头针的方法


#warning 注意:这里有一个问题,不可以自定义annotationView,不知道哪里出了问题...所以annotationView也点击不了....因为不能给它添加UIControl的类...

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
        //大头针的创建类似于tabeView 都用到重用池  也可以不用,自己看内存.....
        static NSString *string = @"annotation";
        MKAnnotationView *annotationView = [self.mapView dequeueReusableAnnotationViewWithIdentifier:string];
        
        if (annotation == nil) {
            annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:string];
        }
        //其他属性自己看
        annotationView.canShowCallout = YES;
        //        //    annotationView.leftCalloutAccessoryView = self.calloutBtn;
        //        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        //        //    rightButton.tag = 2;
        //        annotationView.rightCalloutAccessoryView = rightButton;
        
        return annotationView;
        
    } else {
        
        return nil;
        
    }
    
}




- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
